package it.slkfarm.android;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import it.slkfarm.bean.Crop;
import it.slkfarm.bean.Farm;
import it.slkfarm.bean.Farmer;
import it.slkfarm.bean.ProductionBean;
import it.slkfarm.gps.GpsTracker;
import it.slkfarm.helpers.DialogBuilder;
import it.slkfarm.http.HttpConnector;
import it.slkfarm.log.LogData;
import it.slkfarm.log.SendLog;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class Login extends Base implements OnClickListener, Runnable
{
	/**
	 * @uml.property  name="login"
	 * @uml.associationEnd  
	 */
	private Button login;
	/**
	 * @uml.property  name="register"
	 * @uml.associationEnd  
	 */
	private Button register;
	/**
	 * @uml.property  name="exit"
	 * @uml.associationEnd  
	 */
	private Button exit;
	/**
	 * @uml.property  name="changeLanguage"
	 * @uml.associationEnd  
	 */
	private Button changeLanguage;
	/**
	 * @uml.property  name="pin"
	 * @uml.associationEnd  
	 */
	private EditText pin;
	/**
	 * @uml.property  name="phone"
	 * @uml.associationEnd  
	 */
	private EditText phone;
	/**
	 * @uml.property  name="builder"
	 * @uml.associationEnd  
	 */
	private DialogBuilder builder;
	/**
	 * @uml.property  name="dialog"
	 * @uml.associationEnd  
	 */
	private Dialog dialog;
	/**
	 * @uml.property  name="progress"
	 * @uml.associationEnd  
	 */
	private Dialog progress;
	/**
	 * @uml.property  name="labelProgress"
	 * @uml.associationEnd  
	 */
	private TextView labelProgress;
	/**
	 * @uml.property  name="farmer"
	 * @uml.associationEnd  
	 */
	private Farmer farmer;
	/**
	 * @uml.property  name="addFarm"
	 */
	private boolean addFarm = false;
	/**
	 * @uml.property  name="farmList"
	 * @uml.associationEnd  multiplicity="(0 -1)" elementType="it.slkfarm.bean.Farm"
	 */
	private List<Farm> farmList;
	/**
	 * @uml.property  name="resultPin"
	 */
	private String resultPin;
	/**
	 * @uml.property  name="resultPhoneNumber"
	 */
	private String resultPhoneNumber;
	/**
	 * @uml.property  name="farmName"
	 */
	private String farmName;
	/**
	 * @uml.property  name="longitude"
	 */
	private Double longitude;
	/**
	 * @uml.property  name="latitude"
	 */
	private Double latitude;
	/**
	 * @uml.property  name="tf"
	 * @uml.associationEnd  
	 */
	private Typeface tf;
	/**
	 * @uml.property  name="productionList"
	 * @uml.associationEnd  multiplicity="(0 -1)" elementType="it.slkfarm.bean.ProductionBean"
	 */
	private List<ProductionBean> productionList;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
		farmer = new Farmer();
        setContentView(R.layout.login);
        tf = getTypeface();
        TextView tv = (TextView) findViewById(R.id.tvLoginTitle);
        tv.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/KMKDSP__.ttf"));
        login = (Button) findViewById(R.id.btnLogin);
        login.setTypeface(tf);
        login.setOnClickListener(this);
        register = (Button) findViewById(R.id.btnRegister);
        register.setTypeface(tf);
        register.setOnClickListener(this);
        register.setEnabled(true);
        register.setBackgroundResource(R.drawable.button_disabled);
        exit = (Button) findViewById(R.id.btnLoginExit);
        exit.setTypeface(tf);
        exit.setOnClickListener(this);
        changeLanguage = (Button) findViewById(R.id.btnChangeLanguage);
        changeLanguage.setTypeface(tf);
        changeLanguage.setOnClickListener(this);
        pin = (EditText) findViewById(R.id.etPinLogin);
        pin.setTypeface(tf);
        phone = (EditText) findViewById(R.id.etPhoneLogin);
        phone.setTypeface(tf);
        builder = new DialogBuilder(this, dbAdapter.getSetLanguage());
        GpsTracker gps = new GpsTracker(this);
        if(!gps.isProviderEnabled())
        {
        	gps.stopUsingGps();
        	Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        	dialog = builder.createDialog(R.string.attention, R.string.error_provider_gps, intent, Login.this);
        	dialog.show();
        }
        
        pin.addTextChangedListener(new TextWatcher() 
        {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) 
			{}
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) 
			{
				pin.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/KMKDSP__.ttf"));
			}
			
			public void afterTextChanged(Editable s) 
			{}
		});
        
        phone.addTextChangedListener(new TextWatcher() 
        {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				phone.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/KMKDSP__.ttf"));
				
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
        //pin.setText("1234");
        //phone.setText("123456789");
    }
	
	public void onClick(View v) 
	{
		if (v.getId() == login.getId())
		{
			resultPin = pin.getText().toString();
			resultPhoneNumber = phone.getText().toString();
			
			//CONTROLLO LUNGHEZZA SU ENTRAMBI I CAMPI
			if (resultPin.length() < 4 && resultPhoneNumber.length() < 9)
			{
				LogData log = new LogData("Login","Button Login","Error length pin and phonenumber");
				logger.appendLog(log);
				Toast t = builder.createToast(R.string.error_length_pin_phone, null, this);
				t.show();
			}
			else
			{
				if (resultPin.length() < 4)
				{
					LogData log = new LogData("Login","Button Login","Error length pin");
					logger.appendLog(log);
					Toast t = builder.createToast(R.string.error_length_pin, null, this);
					t.show();
				}
				else if (resultPhoneNumber.length() < 9)
				{
					LogData log = new LogData("Login","Button Login","Error length phonenumber");
					logger.appendLog(log);
					Toast t = builder.createToast(R.string.error_length_phone, null, this);
					t.show();
					
				}
				else
				{
					LogData log = new LogData("Login","Button Login","Connecting to server");
					logger.appendLog(log);
					progress = builder.createProgressDialog();
					labelProgress = (TextView) progress.findViewById(R.id.tvCustomProgressLabel);
					progress.show();
					new Thread(this).start();		
				}
			}
		}
		else if (v.getId() == register.getId())
		{
			LogData log = new LogData("Login","Button Register","Start new registration");
			logger.appendLog(log);
			Intent i = new Intent(Login.this,Registration.class);
			startActivity(i);
			finish();
		}
		else if (v.getId() == exit.getId())
		{
			stopService();
			finish();
		}
		else if (v.getId() == changeLanguage.getId())
		{
			Intent i = new Intent(Login.this, ChooseLanguage.class);
			i.putExtra(getPackageName() + ".change", true);
			finish();
			startActivity(i);
		}

		
	}
	
	/**
	 * @uml.property  name="handler"
	 * @uml.associationEnd  multiplicity="(1 1)"
	 */
	private Handler handler = new Handler() 
	{
        @Override
        public void handleMessage(Message msg) 
        {
        	String message = (String) msg.obj;
        	if (message.equalsIgnoreCase("START"))
        	{
        		labelProgress.setText(R.string.waiting);
        	}
        	else if (message.equalsIgnoreCase("NO_CONNECTION"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_noconnection, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("SERVER_NO"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_server_no, null, null);
        		dialog.show();
        	}
        	
        	else if (message.equalsIgnoreCase("LOGIN_ERROR_PHONE"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_login_error_phone, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("LOGIN_ERROR_PIN"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_login_error_pin, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("LOADING_FARM"))
        	{
        		LogData log = new LogData("Login","Login successfull","Login with this account: " +resultPhoneNumber + " - " +resultPin);
				logger.appendLog(log);
        		progress.dismiss();
        		dialog = builder.creatSelectDialog(farmList, farmer, Login.this);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("ERROR_UPDATE_KEY"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_error_update_key, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("ERROR_GET_FARM"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_error_get_farm, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("ERROR_STORAGE"))
        	{
        		progress.dismiss();
        		dialog = builder.createDialog(R.string.error, R.string.handler_error_storage, null, null);
        		dialog.show();
        	}
        	else if (message.equalsIgnoreCase("DOWNLOAD_CROP"))
        	{
        		labelProgress.setText(R.string.update_crops);
        	}
        	else if (message.equalsIgnoreCase("ERROR_CROP"))
			{
				progress.dismiss();
				Dialog dialog = builder.createDialog(R.string.error, R.string.handler_error_crop, null, null);
				dialog.show();
			}
        	else if (message.equalsIgnoreCase("ERROR_STORAGE_CROP"))
			{
				progress.dismiss();
				Dialog dialog = builder.createDialog(R.string.error, R.string.handler_error_storage_crop, null, null);
				dialog.show();
			}
        }
	};    

	public void run() 
	{
		if (addFarm)
		{
			HttpConnector connector = new HttpConnector();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
			nameValuePairs.add(new BasicNameValuePair("tag", TAG_ADD_FARM));
			nameValuePairs.add(new BasicNameValuePair("phonenumber",resultPhoneNumber));
			nameValuePairs.add(new BasicNameValuePair("pin",resultPin));
			nameValuePairs.add(new BasicNameValuePair("farmnane", farmName));
			nameValuePairs.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
			nameValuePairs.add(new BasicNameValuePair("longitude",String.valueOf(longitude)));
			nameValuePairs.add(new BasicNameValuePair("secretkey", farmer.getSecretKey()));
			try 
			{
				if (connector.connect(WEB_SERVICE_URL_REGISTRATION, nameValuePairs) == 200)
				{
					JSONObject json = connector.getJson();
					int farmId = json.getJSONObject("user").getJSONObject("farm").getInt("farmid");
					int agro = json.getJSONObject("user").getJSONObject("farm").getInt("agro_ecological_regions_id");
					Farm farm = new Farm();
					farm.setId(farmId);
					farm.setName(farmName);
					farm.setFarmerId(farmer.getId());
					farm.setAgroGeolocigalRegionId(agro);
					farm.setLatitude(latitude);
					farm.setLongitude(longitude);
					if (dbAdapter.addFarm(farm) != -1)
					{
						//ADDFARM OK
						farmList = dbAdapter.getFarmList(farmer.getId());
						if (farmList.size() == 0)
						{
							//ERRORE RECUPERO FARM
							sendHandlerMessage("ERROR_GET_FARM");
						}
						else
						{
							sendHandlerMessage("LOADING_FARM");
						}
					}
					else
					{
						//ERROR ADDFARM
						sendHandlerMessage("ERROR_STORAGE");
					}
				}
				else
				{
					LogData log = new LogData("Login","Server","Can't connect to server");
					logger.appendLog(log);
					sendHandlerMessage("SERVER_NO");
				}
			} 
			catch (ClientProtocolException e) 
			{
				
				sendHandlerMessage("SERVER_NO");
				e.printStackTrace();
			} 
			catch (IOException e) 
			{
				
				sendHandlerMessage("SERVER_NO");
				e.printStackTrace();
			} 
			catch (IllegalStateException e) 
			{
				sendHandlerMessage("SERVER_NO");
				e.printStackTrace();
			} 
			catch (JSONException e) 
			{
				e.printStackTrace();
			}
		}
	    else if (!addFarm)
		{
			sendHandlerMessage("START");
			try 
			{
				Thread.sleep(1000);
			} 
			catch (InterruptedException e1) 
			{
				e1.printStackTrace();
			}
			//Controllo Connessione
			ConnectivityManager conManager = ((ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE));
			boolean isWifiEnabled = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
			boolean isMobileEnabled = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
			if (!isWifiEnabled && !isMobileEnabled)
			{
				sendHandlerMessage("NO_CONNECTION");
			}
			else
			{	
				HttpConnector connector = new HttpConnector();
				try 
				{
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
					nameValuePairs.add(new BasicNameValuePair("tag", TAG_LOGIN));
					nameValuePairs.add(new BasicNameValuePair("phonenumber",resultPhoneNumber));
					nameValuePairs.add(new BasicNameValuePair("pin",resultPin));
					if (connector.connect(WEB_SERVICE_URL_LOGIN, nameValuePairs) == 200)
					{
						JSONObject json = connector.getJson();
						Log.i("json login", json.toString());
						int error = json.getInt("error");
						if (error == 0)
						{
							farmer = dbAdapter.getFarmer(resultPin, resultPhoneNumber);
							if (farmer == null)
							{
								farmer = new Farmer();
								//FARMER NON REGISTRATO
								//LEGGO I DATI DEL FARMER DA JSON
								JSONObject farmerJson = json.getJSONObject("user").getJSONObject("farmer");
								Iterator iterator = farmerJson.keys();
								while(iterator.hasNext())
								{
									String key = (String) iterator.next();
									if (key.equalsIgnoreCase("id"))
										farmer.setId(farmerJson.getInt(key));
									else if (key.equalsIgnoreCase("firstname"))
										farmer.setFirstname(farmerJson.getString(key));
									else if (key.equalsIgnoreCase("lastname"))
										farmer.setLastname(farmerJson.getString(key));
									else if (key.equalsIgnoreCase("secretkey"))
										farmer.setSecretKey(farmerJson.getString(key));
									else if (key.equalsIgnoreCase("email"))
										farmer.setSecretKey(farmerJson.getString(key));
									
								}
								farmer.setPin(resultPin);
								farmList = new ArrayList<Farm>();
								
								JSONObject listFarm = json.getJSONObject("user").getJSONObject("farm");
								Iterator keyFarm = listFarm.keys();
								int i=0;
								while (keyFarm.hasNext())
								{
									String dynamicKey = (String) keyFarm.next();
									JSONObject farm = listFarm.getJSONObject(dynamicKey);
									Farm f = new Farm();
									f.setId(farm.getInt("id"));
									f.setName(farm.getString("name"));
									f.setAgroGeolocigalRegionId(farm.getInt("agro_ecological_regions_id"));
									f.setFarmerId(farmer.getId());
									f.setLatitude(farm.getDouble("latitude"));
									f.setLongitude(farm.getDouble("longitude"));
									if (farm.has("production"))
									{
										productionList = new ArrayList<ProductionBean>();
										JSONObject production = farm.getJSONObject("production");
										Iterator keyProduction = production.keys();
										while (keyProduction.hasNext())
										{
											dynamicKey = (String) keyProduction.next();
											JSONObject productionBean = production.getJSONObject(dynamicKey);
											ProductionBean p = new ProductionBean();
											p.setProductionId(productionBean.getInt("id"));
											p.setCropId(productionBean.getInt("crop_id"));
											p.setCultivarId(productionBean.getInt("cultivar_id"));
											p.setQuantity(productionBean.getInt("quantity"));
											p.setUpdate(false);
											p.setFarmId(f.getId());
											productionList.add(p);
										}
									}
									else
									{
										productionList = null;
									}
									f.setListProduction(productionList);
									farmList.add(f);
								}
								LogData log = new LogData("Login","Json","Get farmer and farm info");
								logger.appendLog(log);

								//MEMORIZZO FARMER, FARMLIST, NUMERO DI TELEFONO, CROPS E PRODUZIONE
								if (dbAdapter.register(farmer, farmList, resultPhoneNumber) != 0)
								{
									log = new LogData("Login","Database","Save farmer and farm info");
									logger.appendLog(log);
									sendHandlerMessage("DOWNLOAD_CROP");
									boolean[] check = new boolean[farmList.size()+1];
									check[0] = true;
									for (i=0; i<farmList.size();i++)
									{
										farmList.get(i).setListProduction(null);
										check[i+1] = getCrops(farmList.get(i));
									}
									for (i=1; i<=farmList.size(); i++)
										check[0] = check[0] & check[i];
									if (check[0])
										sendHandlerMessage("LOADING_FARM");
									else
										sendHandlerMessage("SERVER_NO");
								}
								else
								{
									log = new LogData("Login","Database","Error saving farmer and farm info");
									logger.appendLog(log);
									sendHandlerMessage("ERROR_STORAGE");
								}	
							}
							else
							{
								//FARM REGISTRATO
								JSONObject farmerJson = json.getJSONObject("user").getJSONObject("farmer");
								String secretKey = farmerJson.getString("secretkey");
								int n = dbAdapter.updateSecretKey(farmer.getId(), secretKey);
								if (n != -1)
								{
									LogData log = new LogData("Login","Database","Update secret key");
									logger.appendLog(log);
									//UPDATE OK
									//LISTA DELLE FARM
									farmer.setSecretKey(secretKey);
									farmList = dbAdapter.getFarmList(farmer.getId());
									if (farmList.size() == 0)
									{
										//ERRORE RECUPERO FARM
										log = new LogData("Login","Database","Can't get farm list");
										logger.appendLog(log);
										sendHandlerMessage("ERROR_GET_FARM");
									}
									else
									{
										//CONTROLLO SE NON VI SONO VARIAZIONE DI FARM E DI PRODUZIONE
										JSONObject listFarm = json.getJSONObject("user").getJSONObject("farm");
										Iterator keyFarm = listFarm.keys();
										while (keyFarm.hasNext())
										{
											String dynamicKey = (String) keyFarm.next();
											JSONObject farm = listFarm.getJSONObject(dynamicKey);
											Farm f = new Farm();
											f.setId(farm.getInt("id"));
											if (!dbAdapter.haveFarm(f.getId()))
											{
												f.setName(farm.getString("name"));
												f.setAgroGeolocigalRegionId(farm.getInt("agro_ecological_regions_id"));
												f.setFarmerId(farmer.getId());
												f.setLatitude(farm.getDouble("latitude"));
												f.setLongitude(farm.getDouble("longitude"));
												long res = dbAdapter.addFarm(f);
												if (res == -1)
													sendHandlerMessage("ERROR_STORAGE");
												else
													farmList.add(f);
											}
											if (farm.has("production"))
											{
												productionList = new ArrayList<ProductionBean>();
												JSONObject production = farm.getJSONObject("production");
												Iterator keyProduction = production.keys();
												while (keyProduction.hasNext())
												{
													dynamicKey = (String) keyProduction.next();
													JSONObject productionBean = production.getJSONObject(dynamicKey);
													ProductionBean p = new ProductionBean();
													p.setProductionId(productionBean.getInt("id"));
													p.setCropId(productionBean.getInt("crop_id"));
													p.setCultivarId(productionBean.getInt("cultivar_id"));
													p.setQuantity(productionBean.getInt("quantity"));
													p.setFarmId(f.getId());
													if (p.getProductionId() != dbAdapter.getProductionId(p.getCultivarId(), p.getCropId(), p.getFarmId()))
													{
														p.setUpdate(false);
														productionList.add(p);
													}	
													else
													{
														if (p.getQuantity() != dbAdapter.getQuantity(p.getProductionId()))
														{
															p.setUpdate(true);
															productionList.add(p);
														}
													}
												}
											}
											else
											{
												productionList = null;
											}
											if (productionList != null)
											{
												if (productionList.size()>0)
												{
													
													for (int a=0; a<productionList.size(); a++)
														if (!dbAdapter.insertOrUpdateProduction(productionList.get(a)));
															sendHandlerMessage("ERROR_STORAGE");
												}
											}
										}	
										log = new LogData("Login","Database","Load farm");
										logger.appendLog(log);
										sendHandlerMessage("DOWNLOAD_CROP");
										boolean[] check = new boolean[farmList.size()+1];
										check[0] = true;
										for (int i=0; i<farmList.size();i++)
											check[i+1] = getCrops(farmList.get(i));
										for (int i=1; i<=farmList.size(); i++)
											check[0] = check[0] & check[i];
										if (check[0])
											sendHandlerMessage("LOADING_FARM");
										else
											sendHandlerMessage("SERVER_NO");
									}
								}
								else
								{
									//UPDATE NO
									LogData log = new LogData("Login","Database","Can't update secret key");
									logger.appendLog(log);
									sendHandlerMessage("ERROR_UPDATE_KEY");
								}
									
							}
						}
						else if (error == 2)
						{
							//ERRORE PHONE NUMBER
							LogData log = new LogData("Login","Json error","Phone not found");
							logger.appendLog(log);
							sendHandlerMessage("LOGIN_ERROR_PHONE");
						}
						else if (error == 3)
						{
							//ERRORE PIN
							LogData log = new LogData("Login","Json error","Pin incorrect");
							logger.appendLog(log);
							sendHandlerMessage("LOGIN_ERROR_PIN");
						}
					}
					else
					{
						LogData log = new LogData("Login","Server","Can't connect to server");
						logger.appendLog(log);
						sendHandlerMessage("SERVER_NO");
					}
				} 
				catch (ClientProtocolException e) 
				{
					sendHandlerMessage("SERVER_NO");
					e.printStackTrace();
				} 
				catch (IOException e) 
				{
					sendHandlerMessage("SERVER_NO");
					e.printStackTrace();
				} 
				catch (IllegalStateException e) 
				{
					sendHandlerMessage("SERVER_NO");
					e.printStackTrace();
				} 
				catch (JSONException e) 
				{
					e.printStackTrace();
				}
			}
		}
	}  
	
	private boolean getCrops(Farm farm)
	{
		List<Crop> cropList = new ArrayList<Crop>();
		HttpConnector connector = new HttpConnector();
		try 
		{
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			int lang = dbAdapter.getSetLanguage();
			nameValuePairs.add(new BasicNameValuePair("tag", TAG_GET_CROPS_TEST));
			nameValuePairs.add(new BasicNameValuePair("secretkey",farmer.getSecretKey()));
			nameValuePairs.add(new BasicNameValuePair("farmid",String.valueOf(farm.getId())));
			if (lang == 1)
				nameValuePairs.add(new BasicNameValuePair("lang",LOCALE_EN));
			else
				nameValuePairs.add(new BasicNameValuePair("lang", LOCALE_SRILANKA));
			int valueConnect = connector.connect(WEB_SERVICE_URL_CROP, nameValuePairs);
			sendHandlerMessage("TEST");
			Thread.sleep(10000);
			if (valueConnect == 200)
			{
				JSONObject jsonObject = connector.getJson();
				Log.i("crops", jsonObject.toString());
				int error = jsonObject.getInt("error");
				int success = jsonObject.getInt("success");
				if (error == 0 && success == 1)
				{	
					cropList = new ArrayList<Crop>();
					int numberOfCrops = jsonObject.getInt("number_of_crops");
					int i = 1;
					JSONObject cropInfo = jsonObject.getJSONObject("cropInfo");
					Iterator keyCropInfo = cropInfo.keys();
					//CICLO SU CROP_INFO
					while (keyCropInfo.hasNext())
					{
						String dynamicKey = (String) keyCropInfo.next();
						JSONObject type = cropInfo.getJSONObject(dynamicKey);
						Iterator keyType = type.keys();
						//CICLO SUI TIPI
						while(keyType.hasNext())
						{
							dynamicKey = (String) keyType.next();
							if (!dynamicKey.equalsIgnoreCase("label"))
							{
								JSONObject cultivar = type.getJSONObject(dynamicKey).getJSONObject("cultivar");
								Iterator keyCultivar = cultivar.keys();
								//CICLO SUI CROP
								while (keyCultivar.hasNext())
								{
									dynamicKey = (String) keyCultivar.next();
									JSONObject singleCrop = cultivar.getJSONObject(dynamicKey);
									Crop crop = new Crop();
									crop.setCropId(singleCrop.getInt("cropId"));
									crop.setCultivarId(singleCrop.getInt("cultivarId"));
									crop.setCropType(singleCrop.getString("cropType"));
									crop.setCropName(singleCrop.getString("cropName"));
									crop.setCultivarName(singleCrop.getString("cultivarName"));
									JSONObject production = singleCrop.getJSONObject("production");
									if(!production.isNull("maxProduction")) 
										crop.setMaxProduction(production.getInt("maxProduction"));
									else
										crop.setMaxProduction(0);
									if (!production.isNull("currentProduction"))
										crop.setCurrentProduction(production.getInt("currentProduction"));
									else
										crop.setCurrentProduction(0);
									if (!production.isNull("percentageOfProduction"))
									{
										double percentage = production.getDouble("percentageOfProduction");
										percentage = Math.floor(percentage*100);
										percentage = percentage / 100;
										crop.setPercentageProduction(percentage);
									}
									else
										crop.setPercentageProduction(0.0);
									String imageName = "";
									imageName = "img"+String.valueOf(crop.getCropId())+String.valueOf(crop.getCultivarId());
									connector.getImage(singleCrop.getString("images"), imageName);
									JSONObject characteristics = singleCrop.getJSONObject("characteristics");
									String app = characteristics.getString("size");
									if (app.equalsIgnoreCase("") || app.equalsIgnoreCase("null"))
										crop.setSize("?");
									else
										crop.setSize(app);
									app = characteristics.getString("weight");
									if (app.equalsIgnoreCase("") || app.equalsIgnoreCase("null"))
										crop.setWeight("?");
									else
										crop.setWeight(app);
									app = characteristics.getString("color");
									if (app.equalsIgnoreCase("") || app.equalsIgnoreCase("null"))
										crop.setColor("?");
									else
										crop.setColor(app);
									cropList.add(crop);
								}
							}	
						}
					}
					LogData log = new LogData("Menu","Json","Get crops list");
					logger.appendLog(log);
					//MEMORIZZARLI
					if (dbAdapter.registerCrops(cropList, farm.getAgroGeolocigalRegionId()) !=0)
					{
						log = new LogData("Menu","Database","Save crops list");
						logger.appendLog(log);
						return true;
					}
					else
					{
						log = new LogData("Menu","Database","Can't save crops list");
						logger.appendLog(log);
						sendHandlerMessage("ERROR_STORAGE_CROP");
						return false;
					}
				}
				else
				{
					LogData log = new LogData("Menu","Json error","Can't get crops list");
					logger.appendLog(log);
					sendHandlerMessage("ERROR_CROP");
					return false;
				}
			}
			else
			{
				LogData log = new LogData("Menu","Server","Can't connect to server");
				logger.appendLog(log);
				sendHandlerMessage("SERVER_NO");
				return false;
			}
			
		} 
		catch (ClientProtocolException e) 
		{
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
			return false;
		} 
		catch (IOException e) 
		{
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
			return false;
		} catch (IllegalStateException e) {
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
			return false;
		}
	}
		
	private void sendHandlerMessage(String message)
	{
		Message msg = handler.obtainMessage();
		msg.obj = message;
		handler.sendMessage(msg);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK)
		{
			farmName = data.getStringExtra(getPackageName() + ".name");
			latitude = data.getDoubleExtra(getPackageName() + ".latitude", 0);
			longitude = data.getDoubleExtra(getPackageName() + ".longitude", 0);
			addFarm = true;
			progress = builder.createProgressDialog();
			progress.show();
			new Thread(this).start();			
		}
	}	
}
